package com.pro.schedule.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pro.schedule.entity.User;
import com.pro.schedule.filter.ResultUtil;
import com.pro.schedule.filter.TokenUtil;
import com.pro.schedule.mapper.UserMapper;
import com.pro.schedule.service.UserService;
import com.pro.schedule.util.SnowflakeIdWorker;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    TokenUtil tokenUtil;
    @Resource
    ResultUtil resultUtil;
    @Resource
    UserMapper userMapper;

    @Override
    public String loginUser(User user) throws Exception {
        User newUser;
        if(Objects.equals(user.getUserPhone(), "")){
            newUser = userMapper.loginUser(user.getUserAccount(), user.getUserPassword());
            if(newUser == null){
                throw new Exception("用户名或密码错误");
            }
        }else{
            newUser = userMapper.loginUserByPhone(user.getUserPhone());
            if(newUser == null){
                throw new Exception("手机号未注册");
            }
        }
        return tokenUtil.getToken(newUser);
    }

    @Override
    public User getUserInfo(String token) {
        Long userId = resultUtil.getUserId(token);
        User user = userMapper.selectById(userId);
        user.setUserPassword("");
        return user;
    }

    @Override
    public String saveOrUpdateUser(User user, String token) throws Exception {
        if (token == null || token.equals("")) {
            QueryWrapper<User> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("user_account", user.getUserAccount());
            if(userMapper.selectCount(wrapper1)>0){
                throw new Exception("账号已存在");
            }
            QueryWrapper<User> wrapper2 = new QueryWrapper<>();
            wrapper2.eq("user_phone", user.getUserPhone());
            if(userMapper.selectCount(wrapper2)>0){
                throw new Exception("手机号已注册");
            }
            SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1L,1L);
            long userId = snowflakeIdWorker.nextId();
            user.setUserId(userId);
            int result = userMapper.insert(user);
            if (result > 0) {
                return tokenUtil.getToken(user);
            }
        } else {
            Map<String, String> userMap = tokenUtil.parseToken(token);
            Long userId = Long.parseLong(userMap.get("userId"));
            user.setUserId(userId);
            user.setUserPassword(userMapper.selectById(userId).getUserPassword());
            user.setUserAccount(userMapper.selectById(userId).getUserAccount());
            int result = userMapper.updateById(user);
            if (result > 0) {
                return tokenUtil.getToken(user);
            }
        }
        return null;
    }


    @Override
    public String changePassword(String token, String newPassword, String userPassword) throws Exception {
        Long userId = resultUtil.getUserId(token);
        User user = userMapper.selectById(userId);
        if (Objects.equals(userPassword, user.getUserPassword())) {
            user.setUserPassword(newPassword);
            int result = userMapper.updateById(user);
            return resultUtil.getResult(result, "修改密码");
        } else {
            throw new Exception("旧密码错误");
        }
    }

    @Override
    public String forgetPassword(String userPhone, String newPassword) throws Exception {
        User newUser = userMapper.loginUserByPhone(userPhone);
        newUser.setUserPassword(newPassword);
        int result = userMapper.updateById(newUser);
        return resultUtil.getResult(result, "修改密码");
    }

    @Override
    public String getCode(String userPhone) throws Exception {
        return "1234";
    }

    @Override
    public String uploadAvatar(MultipartFile file, String path, String token) throws Exception {
        saveFile(file,path);
        Long userId = resultUtil.getUserId(token);
        User user =userMapper.selectById(userId);
        String userAvatar = "http://192.168.164.1:5050/upload/"+file.getOriginalFilename();
        user.setUserAvatar(userAvatar);
        int result = userMapper.updateById(user);
        if(result>0){
            return tokenUtil.getToken(user);
        }
        return null;
    }
    public void saveFile(MultipartFile file,String path)throws IOException{
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
        String newPath=path+'/';
        File newDir = new File(newPath);
        if(!newDir.exists()){
            newDir.mkdir();
        }
        File newFile=new File(newPath+file.getOriginalFilename());
        file.transferTo(newFile);
    }
}
